﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TPOJ.IDAL;
using TPOJ.Model;

namespace TPOJ.LINQDAL
{
    public class AccountDAO : IAccountDAO
    {
        public Account GetAccountByName(string accountName)
        {
            Account result;
            using (var entities = new TPOJSERVICESEntities())
            {
                var query = from a in entities.Accounts
                            where a.Name == accountName
                            select a;
                result = query.First();
            }
            return result;
        }

        public Account GetAccount(int userId)
        {
            Account result;
            using (var entities = new TPOJSERVICESEntities())
            {
                var query = from a in entities.Accounts
                            where a.UniqueId == userId
                            select a;
                result = query.First();
            }
            return result;
        }

        public int GetAccountRank(int userId)
        {
            int result = 0;
            using (var entities = new TPOJSERVICESEntities())
            {
                var query = from a in entities.Accounts
                            orderby a.Solved descending, a.Submits ascending
                            select a.UniqueId;
                result = Array.IndexOf(query.ToArray(), userId) + 1;
            }
            return result;
        }

        public IList<Tuple<int, Account>> GetNeighboursByUserId(int userId, out int rank)
        {
            var result = new List<Tuple<int, Account>>();

            using (var entities = new TPOJSERVICESEntities())
            {
                var query = from a in entities.Accounts
                            orderby a.Solved descending, a.Submits ascending
                            select a;
                rank = Array.IndexOf(query.Select(a => a.UniqueId).ToArray(), userId) + 1;
                var rankArray = query.ToArray();

                for (int i = rank - 3 ; i <= rank + 3; i++)
                {
                    int j = i - 1;
                    if (j >= 0 && j<rankArray.Length)
                        result.Add(new Tuple<int, Account>(i, rankArray[j]));
                }
            }
            return result;
        }

    }
}
